package com.zjzywl.smoke.controller;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSONArray;
import com.zjzywl.smoke.config.AppConfig;
import com.zjzywl.smoke.entity.Building;
import com.zjzywl.smoke.entity.BuildingInspectionRecord;
import com.zjzywl.smoke.util.Columns;
import com.zjzywl.smoke.util.WebResult;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping(value = "/building")
public class BuildingController extends BaseController {
    @Autowired
    private AppConfig appConfig;
    // 同步锁对象
    Object obj = new Object();

    /*
     * 添加，修改高层建筑
     */
    @PostMapping(value = "/save")
    public WebResult save(Building building, @RequestParam("orgId") Integer orgId, MultipartFile file) {
        try {
            if (file != null) {
                String photoUrl = executeUpload(file, "building");
                building.setPhotoUrl(photoUrl);
            }
            ResponseEntity<Building> history = appConfig.restTemplate()
                    .postForEntity(appConfig.getGetDataIp() + "/building/save/" + orgId, building, Building.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            // 打印出错
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    // 删除建筑
    @DeleteMapping(value = "/delete/{id}")
    public WebResult delete(@PathVariable("id") Integer id) {
        try {
            appConfig.restTemplate().delete(appConfig.getGetDataIp() + "/building/delete/" + id);
            return WebResult.OK();
        } catch (Exception e) {
            // 打印出错
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }

    }

    // 根据楼房地址名称模糊查询
    @RequestMapping(value = "/getBuildings", method = RequestMethod.GET)
    @ResponseBody
    public WebResult getByUserAndDeviceTypeAndAddressLike(HttpServletRequest request) {
        try {
            String userId = this.getUserId();
            ResponseEntity<Object> history = appConfig.restTemplate().getForEntity(appConfig.getGetDataIp()
                    + "/building/getBuildings/" + userId + "?" + URLDecoder.decode(request.getQueryString(), "utf-8"),
                    Object.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            // 打印出错
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    // 根据OnlyValue查询楼宇信息
    @GetMapping("/getBuildingsByOnlyValue")
    @ResponseBody
    public WebResult getBuildingsByOnlyValue(@RequestParam(value = "onlyValue", required = false) String onlyValue,
            @RequestParam(value = "uuid", required = false) String uuid) throws ParseException, IOException {
        try {
            ResponseEntity<Object> history = appConfig.restTemplate().getForEntity(appConfig.getGetDataIp()
                    + "/building/getBuildingsByOnlyValue?onlyValue=" + onlyValue + "&uuid=" + uuid, Object.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    // 获取所有楼宇信息，在地图上画点
    @GetMapping("/getAllBuildings")
    @ResponseBody
    public WebResult getAllBuildings(@RequestParam(value = "type", required = false) Integer type) {
        try {
            String userId = this.getUserId();
            ResponseEntity<Object> history = appConfig.restTemplate().getForEntity(
                    appConfig.getGetDataIp() + "/building/getAllBuildings/" + userId + "?type=" + type, Object.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    // 获取楼宇巡检列表
    @GetMapping("/getBuildingInspectionRecord")
    @ResponseBody
    public WebResult getBuildings(HttpServletRequest request) {
        try {
            String userId = this.getUserId();
            ResponseEntity<Object> history = appConfig.restTemplate()
                    .getForEntity(appConfig.getGetDataIp() + "/building/getBuildingInspectionRecord?userId=" + userId
                            + "&" + URLDecoder.decode(request.getQueryString(), "utf-8"), Object.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    // 添加楼宇巡检 微信小程序提交
    @PostMapping("/save/buildingInspectionRecord")
    public WebResult saveGetBuildingInspectionRecord(
            @RequestParam("buildingInspectionRecord") String buildingInspectionRecord,
            @RequestParam("orgId") Integer orgId) throws ParseException, IOException {
        try {
            String name = null;
            if (buildingInspectionRecord != null && !"".equals(buildingInspectionRecord)) {
                name = buildingInspectionRecord.substring(1, buildingInspectionRecord.length() - 1);
            }
            List<BuildingInspectionRecord> jsonToList = jsonToList(name, BuildingInspectionRecord.class);
            ResponseEntity<BuildingInspectionRecord> history = appConfig.restTemplate().postForEntity(
                    appConfig.getGetDataIp() + "/building/save/buildingInspectionRecord?orgId=" + orgId, jsonToList,
                    BuildingInspectionRecord.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    // 添加楼宇巡检（提交无问题的接口） 微信小程序提交
    @PostMapping("/save/buildingInspectionRecordNoProblem")
    public WebResult saveBuildingInspectionRecordNoProblem(
            @RequestParam("buildingInspectionRecord") String buildingInspectionRecord,
            @RequestParam("orgId") Integer orgId) {
        try {
            String name = null;
            if (buildingInspectionRecord != null && !"".equals(buildingInspectionRecord)) {
                name = buildingInspectionRecord.substring(1, buildingInspectionRecord.length() - 1);
            }
            List<BuildingInspectionRecord> jsonToList = jsonToList(name, BuildingInspectionRecord.class);
            ResponseEntity<BuildingInspectionRecord> history = appConfig.restTemplate().postForEntity(
                    appConfig.getGetDataIp() + "/building/save/buildingInspectionRecordNoProblem?orgId=" + orgId,
                    jsonToList.get(0), BuildingInspectionRecord.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    // 添加楼宇巡检照片 微信小程序提交
    @PostMapping("/save/buildingInspectionRecordPhoto")
    public WebResult saveGetbuildingInspectionRecordPhoto(
            @RequestParam("buildingInspectionRecordId") Integer buildingInspectionRecordId, MultipartFile file,
            @RequestParam("trouble") Integer trouble) throws ParseException, IOException {
        try {
            while (true) {
                synchronized (obj) {
                    try {
                        String photoUrl = executeUpload(file, "buildingInspectionRecord");
                        ResponseEntity<BuildingInspectionRecord> history = appConfig.restTemplate()
                                .getForEntity(appConfig.getGetDataIp()
                                        + "/building/save/buildingInspectionRecordPhoto?buildingInspectionRecordId="
                                        + buildingInspectionRecordId + "&photoUrl=" + photoUrl + "&trouble=" + trouble,
                                        BuildingInspectionRecord.class);
                        return WebResult.OK(history);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    /**
     * json 转 List<T>
     */
    public static List<BuildingInspectionRecord> jsonToList(String jsonString, Class<BuildingInspectionRecord> clazz) {
        @SuppressWarnings("unchecked")
        List<BuildingInspectionRecord> ts = (List<BuildingInspectionRecord>) JSONArray.parseArray(jsonString, clazz);
        return ts;
    }
    // // 添加楼宇巡检 微信小程序提交
    // @PostMapping("/save/buildingInspectionRecord")
    // public WebResult saveBuildingInspectionRecord(@RequestBody
    // List<BuildingInspectionRecord> buildingInspectionRecord,
    // @RequestParam("orgId") Integer orgId) throws ParseException, IOException {
    // try {
    // ResponseEntity<BuildingInspectionRecord> history =
    // appConfig.restTemplate().postForEntity(
    // appConfig.getGetDataIp() + "/building/save/buildingInspectionRecord?orgId=" +
    // orgId,
    // buildingInspectionRecord, BuildingInspectionRecord.class);
    // return WebResult.OK(history);
    // } catch (Exception e) {
    // e.printStackTrace();
    // return WebResult.FAIL(e.toString());
    // }
    // }

    /*
     * 图片上传方法
     * 
     */
    private String executeUpload(MultipartFile file, String code) throws Exception {
        String uploadDir = getUploadDir() + code + "/";
        // 如果文件不存在，自动创建文件夹
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                logger.error("创建上传目录失败");
            }
        }
        if (file != null) {
            // 文件后缀名
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            // 上传文件名
            String filename = UUID.randomUUID() + suffix;
            // 服务器端保存的文件对象
            File serverFile = new File(uploadDir + filename);
            // 将上传到的文件写入到服务器
            file.transferTo(serverFile);
            return "/upload/" + code + "/" + filename;
        }
        return null;
    }

    // 获取楼层巡检详情
    @GetMapping("/getBuildingInspectionRecordDetails")
    @ResponseBody
    public WebResult getBuildingInspectionRecordDetails(HttpServletRequest request) {
        try {
            String userId = "admin";
            ResponseEntity<Object> history = appConfig.restTemplate()
                    .getForEntity(appConfig.getGetDataIp() + "/building/getBuildingInspectionRecordDetails?userId="
                            + userId + "&" + URLDecoder.decode(request.getQueryString(), "utf-8"), Object.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    // 获取楼层巡检详情
    @GetMapping("/getBuildingInspectionRecordDetailsByBuildingName")
    @ResponseBody
    public WebResult getBuildingInspectionRecordDetailsByBuildingName(HttpServletRequest request) {
        try {
            String userId = "admin";
            ResponseEntity<Object> history = appConfig.restTemplate()
                    .getForEntity(appConfig.getGetDataIp()
                            + "/building/getBuildingInspectionRecordDetailsByBuildingName?userId=" + userId + "&"
                            + URLDecoder.decode(request.getQueryString(), "utf-8"), Object.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    // 获取楼层隐患
    @GetMapping("/getFloorHiddenDanger")
    public WebResult getFloorHiddenDanger(HttpServletRequest request) {
        try {
            ResponseEntity<Object> history = appConfig.restTemplate().getForEntity(appConfig.getGetDataIp()
                    + "/building/getFloorHiddenDanger?" + URLDecoder.decode(request.getQueryString(), "utf-8"),
                    Object.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    // 巡检详情隐患图解详情
    @GetMapping("/getFloorHiddenDangerGraphic")
    public WebResult getFloorHiddenDangerGraphic(@RequestParam("uuid") String uuid) {
        try {
            ResponseEntity<Object> history = appConfig.restTemplate().getForEntity(
                    appConfig.getGetDataIp() + "/building/getFloorHiddenDangerGraphic?uuid=" + uuid, Object.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    // 主页隐患图解详情
    @GetMapping("/getFloorHiddenDangerGraphicByOrgId")
    public WebResult getFloorHiddenDangerGraphicByOrgId() {
        try {
            String userId = this.getUserId();
            ResponseEntity<Object> list = appConfig.restTemplate().getForEntity(
                    appConfig.getGetDataIp() + "/building/getFloorHiddenDangerGraphicByOrgId?userId=" + userId,
                    Object.class);
            return WebResult.OK(list);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    // 异常违规项 接口
    @GetMapping("/getExceptionViolation")
    public WebResult getExceptionViolation() {
        try {
            String userId = this.getUserId();
            ResponseEntity<Object> list = appConfig.restTemplate().getForEntity(
                    appConfig.getGetDataIp() + "/building/getExceptionViolation?userId=" + userId, Object.class);
            return WebResult.OK(list);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    // 异常分布表接口
    @GetMapping("/getExceptionDistribution")
    @ResponseBody
    public WebResult getExceptionDistribution(HttpServletRequest request) {
        try {
            String userId = this.getUserId();
            ResponseEntity<Object> history = appConfig.restTemplate()
                    .getForEntity(appConfig.getGetDataIp() + "/building/getExceptionDistribution?userId=" + userId + "&"
                            + URLDecoder.decode(request.getQueryString(), "utf-8"), Object.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    // 全区巡检结果
    @GetMapping("/getInspectionResults")
    public WebResult getInspectionResults() {
        try {
            String userId = this.getUserId();
            ResponseEntity<Object> history = appConfig.restTemplate().getForEntity(
                    appConfig.getGetDataIp() + "/building/getInspectionResults?userId=" + userId, Object.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    // 异常分布表根据地址或上报人查询接口
    @GetMapping("/getExceptionDistributionSearch")
    public WebResult getExceptionDistributionSearch(
            @RequestParam(value = "queryContent", required = false) String queryContent,
            @RequestParam(value = "trouble", required = false) Integer trouble) {
        try {
            String userId = this.getUserId();
            ResponseEntity<Object> history = appConfig.restTemplate()
                    .getForEntity(appConfig.getGetDataIp() + "/building/getExceptionDistributionSearch?userId=" + userId
                            + "&queryContent=" + queryContent + "&trouble=" + trouble, Object.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    // 首页数据统计接口
    @GetMapping("/getDataStatistics")
    public WebResult getDataStatistics() {
        try {
            String userId = this.getUserId();
            ResponseEntity<Object> history = appConfig.restTemplate().getForEntity(
                    appConfig.getGetDataIp() + "/building/getDataStatistics?userId=" + userId, Object.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    // 获取正常建筑物，异常建筑物的数量
    @GetMapping("/getStateQuantityOfBuildings")
    public WebResult getStateQuantityOfBuildings() {
        try {
            String userId = this.getUserId();
            ResponseEntity<Object> history = appConfig.restTemplate().getForEntity(
                    appConfig.getGetDataIp() + "/building/getStateQuantityOfBuildings?userId=" + userId, Object.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    @ApiOperation("月报表柱状统计图接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "communityName", value = "小区名称", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "belongRegion", value = "所属社区", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "userId", value = "登陆人Id", required = true, paramType = "query", dataType = "int") })
    @GetMapping(value = "/columns")
    public WebResult<List<Columns>> columns(HttpServletRequest request) {
        try {
            String userId = this.getUserId();
            System.out.println(appConfig.getGetDataIp() + "/building/columns?userId=" + userId + "&"
                    + URLDecoder.decode(request.getQueryString(), "utf-8"));
            ResponseEntity<Object> history = appConfig.restTemplate().getForEntity(appConfig.getGetDataIp()
                    + "/building/columns?userId=" + userId + "&" + URLDecoder.decode(request.getQueryString(), "utf-8"),
                    Object.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    // 月报表隐患图解详情
    @GetMapping("/getPieChart")
    public WebResult getPieChart(HttpServletRequest request) {
        try {
            String userId = this.getUserId();
            ResponseEntity<Object> history = appConfig.restTemplate()
                    .getForEntity(appConfig.getGetDataIp() + "/building/getPieChart?userId=" + userId + "&"
                            + URLDecoder.decode(request.getQueryString(), "utf-8"), Object.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

}
